<template>
  <div class="search-page-container">
    <!-- 搜索结果 -->
    <el-card class="search-results">
      <template #header>
        <div class="results-header">
          <h3 v-if="keyword">搜索结果：{{ keyword }}</h3>
          <h3 v-else>搜索结果</h3>
          <el-button 
            type="primary" 
            size="small" 
            @click="$router.push('/article/create')" 
            v-if="isLoggedIn"
          >
            发布文章
          </el-button>
        </div>
      </template>
      
      <!-- 筛选条件 -->
      <div class="filter-options">
        <div class="sort-options">
          <el-radio-group v-model="sortType" size="small" @change="loadSearchResults">
            <el-radio-button value="new">最新发布</el-radio-button>
            <el-radio-button value="hot">最多浏览</el-radio-button>
            <el-radio-button value="comment">最多评论</el-radio-button>
          </el-radio-group>
        </div>
        
        <div class="time-filter">
          <el-select v-model="timeRange" placeholder="时间范围" size="small" @change="loadSearchResults">
            <el-option label="全部时间" value="all"></el-option>
            <el-option label="最近一天" value="day"></el-option>
            <el-option label="最近一周" value="week"></el-option>
            <el-option label="最近一月" value="month"></el-option>
          </el-select>
        </div>
      </div>
      
      <!-- 加载骨架屏 -->
      <div v-if="loading">
        <el-skeleton :rows="3" animated :count="5" />
      </div>
      
      <!-- 空状态 -->
      <el-empty
        v-else-if="articles.length === 0"
        description="未找到相关文章"
      ></el-empty>
      
      <!-- 文章列表内容 -->
      <div v-else>
        <div v-for="article in articles" :key="article.id" class="article-item">
          <div class="article-main">
            <!-- 文章内容 -->
            <div class="article-content">
              <div class="article-info">
                <span class="board-tag">
                  <router-link :to="`/board/${article.boardId}`">
                    {{ getBoardName(article.boardId) }}
                  </router-link>
                </span>
                <router-link :to="`/user/${article.userId}`" class="user-link">
                  <el-avatar :size="24" :src="article.user && article.user.avatarUrl || defaultAvatar"></el-avatar>
                  <span>{{ article.user ? article.user.nickname : '未知用户' }}</span>
                </router-link>
                <span class="post-time">{{ formatDate(article.createTime) }}</span>
              </div>
              
              <router-link :to="`/article/${article.id}`" class="article-title">
                {{ article.title }}
                <span v-if="article.isPinned === 1" class="top-tag">置顶</span>
              </router-link>
              
              <p class="article-summary">{{ article.summary || (article.content ? article.content.substring(0, 100) + '...' : '') }}</p>
            </div>
          </div>
          
          <!-- 文章底部信息 -->
          <div class="article-footer">
            <div class="article-stats">
              <span class="stat-item">
                <el-icon><ViewIcon /></el-icon> {{ article.visitCount || 0 }}
              </span>
              <span class="stat-item">
                <el-icon><ChatDotRound /></el-icon> {{ article.replyCount || 0 }}
              </span>
              <span class="stat-item">
                <el-icon><Star /></el-icon> {{ article.likeCount || 0 }}
              </span>
            </div>
            
            <div class="article-tags" v-if="article.tags">
              <el-tag
                v-for="tag in article.tags.split(',').slice(0, 3)"
                :key="tag"
                size="small"
                type="info"
                effect="plain"
              >
                {{ tag }}
              </el-tag>
            </div>
          </div>
        </div>
      </div>
      
      <!-- 分页 -->
      <div class="pagination-container" v-if="total > 0">
        <el-pagination
          background
          layout="prev, pager, next"
          :total="total"
          :page-size="pageSize"
          :current-page="currentPage"
          @current-change="handlePageChange"
        ></el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { ref, computed, onMounted, watch } from 'vue'
import { useStore } from 'vuex'
import { useRoute } from 'vue-router'
import { View as ViewIcon, ChatDotRound, Star } from '@element-plus/icons-vue'

export default {
  name: 'SearchPage',
  components: {
    ViewIcon,
    ChatDotRound,
    Star
  },
  setup() {
    const store = useStore()
    const route = useRoute()
    
    const loading = ref(true)
    const articles = ref([])
    const total = ref(0)
    const currentPage = ref(1)
    const pageSize = ref(10)
    const sortType = ref('new')
    const timeRange = ref('all')
    const defaultAvatar = require('@/assets/default-avatar.png')
    
    // 从路由参数获取搜索关键词
    const keyword = computed(() => route.query.keyword || '')
    
    // 用户登录状态
    const isLoggedIn = computed(() => store.getters['user/isLoggedIn'])
    
    // 加载搜索结果
    const loadSearchResults = async () => {
      console.log('开始加载搜索结果，关键词:', keyword.value);
      
      if (!keyword.value.trim()) {
        articles.value = []
        total.value = 0
        loading.value = false
        console.log('关键词为空，返回空结果');
        return
      }
      
      loading.value = true
      console.log('搜索参数:', {
        sort: sortType.value,
        timeRange: timeRange.value,
        page: currentPage.value,
        size: pageSize.value,
        keyword: keyword.value
      });
      
      try {
        const response = await store.dispatch('article/getSortedArticles', {
          sort: sortType.value,
          timeRange: timeRange.value,
          page: currentPage.value,
          size: pageSize.value,
          keyword: keyword.value
        })
        
        console.log('搜索结果返回:', response);
        articles.value = response.data || []
        total.value = response.total || 0
      } catch (error) {
        console.error('搜索文章失败:', error)
        articles.value = []
        total.value = 0
      } finally {
        loading.value = false
      }
    }
    
    // 格式化日期
    const formatDate = (dateString) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      const now = new Date()
      const diff = Math.floor((now - date) / 1000)
      
      if (diff < 60) {
        return '刚刚'
      } else if (diff < 3600) {
        return Math.floor(diff / 60) + '分钟前'
      } else if (diff < 86400) {
        return Math.floor(diff / 3600) + '小时前'
      } else if (diff < 2592000) {
        return Math.floor(diff / 86400) + '天前'
      } else if (diff < 31536000) {
        return Math.floor(diff / 2592000) + '个月前'
      } else {
        return Math.floor(diff / 31536000) + '年前'
      }
    }
    
    // 获取板块名称
    const getBoardName = (boardId) => {
      const boardMap = store.getters.boardMap
      return boardMap[boardId] ? boardMap[boardId].name : '未知板块'
    }
    
    // 处理页码变化
    const handlePageChange = (page) => {
      currentPage.value = page
      loadSearchResults()
    }
    
    // 监听路由变化，重新加载搜索结果
    watch(() => route.query.keyword, (newKeyword) => {
      if (newKeyword !== undefined) {
        currentPage.value = 1
        loadSearchResults()
      }
    })
    
    // 初始加载
    onMounted(() => {
      // 加载板块列表
      store.dispatch('fetchBoards')
      
      // 加载搜索结果
      loadSearchResults()
    })
    
    return {
      loading,
      articles,
      total,
      currentPage,
      pageSize,
      sortType,
      timeRange,
      keyword,
      isLoggedIn,
      defaultAvatar,
      loadSearchResults,
      formatDate,
      getBoardName,
      handlePageChange
    }
  }
}
</script>

<style lang="scss" scoped>
.search-page-container {
  max-width: 1000px;
  margin: 20px auto;
  
  .search-results {
    margin-bottom: 20px;
    
    .results-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      h3 {
        margin: 0;
        font-size: 18px;
        font-weight: 500;
      }
    }
    
    .filter-options {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      margin-bottom: 15px;
      gap: 15px;
      
      .sort-options {
        flex-grow: 1;
      }
    }
    
    .article-item {
      padding: 15px 0;
      border-bottom: 1px solid #f0f0f0;
      
      &:last-child {
        border-bottom: none;
      }
      
      .article-main {
        display: flex;
        margin-bottom: 10px;
        
        .article-content {
          flex: 1;
          
          .article-info {
            margin-bottom: 8px;
            font-size: 13px;
            color: #909399;
            display: flex;
            align-items: center;
            flex-wrap: wrap;
            gap: 10px;
            
            .board-tag {
              background-color: #ecf5ff;
              color: #409eff;
              padding: 2px 6px;
              border-radius: 4px;
              font-size: 12px;
              
              a {
                color: inherit;
                text-decoration: none;
                
                &:hover {
                  text-decoration: underline;
                }
              }
            }
            
            .user-link {
              display: flex;
              align-items: center;
              text-decoration: none;
              color: inherit;
              
              span {
                margin-left: 5px;
                
                &:hover {
                  text-decoration: underline;
                }
              }
            }
          }
          
          .article-title {
            display: block;
            font-size: 16px;
            font-weight: 500;
            color: #303133;
            margin-bottom: 8px;
            text-decoration: none;
            
            &:hover {
              color: #409eff;
            }
            
            .top-tag {
              background-color: #f56c6c;
              color: white;
              font-size: 12px;
              padding: 1px 4px;
              border-radius: 2px;
              margin-left: 8px;
              font-weight: normal;
            }
          }
          
          .article-summary {
            color: #606266;
            font-size: 14px;
            margin: 0;
            line-height: 1.5;
            overflow: hidden;
            text-overflow: ellipsis;
            display: -webkit-box;
            -webkit-line-clamp: 2;
            -webkit-box-orient: vertical;
          }
        }
      }
      
      .article-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .article-stats {
          display: flex;
          align-items: center;
          gap: 15px;
          color: #909399;
          font-size: 13px;
          
          .stat-item {
            display: flex;
            align-items: center;
            
            .el-icon {
              margin-right: 3px;
            }
          }
        }
        
        .article-tags {
          display: flex;
          gap: 5px;
          
          .el-tag {
            margin: 0;
          }
        }
      }
    }
    
    .pagination-container {
      margin-top: 20px;
      display: flex;
      justify-content: center;
    }
  }
}

@media (max-width: 768px) {
  .search-page-container {
    padding: 0 15px;
    
    .filter-options {
      flex-direction: column;
      align-items: flex-start;
      
      .sort-options, .time-filter {
        width: 100%;
        margin-bottom: 10px;
      }
    }
    
    .article-item {
      .article-footer {
        flex-direction: column;
        align-items: flex-start;
        
        .article-stats {
          margin-bottom: 10px;
        }
      }
    }
  }
}
</style> 